package main

import "C"

import (
	"fmt"
	"net"
	"sync"
	"sync/atomic"
	"time"
)

const PORT = 12730
const HOST = "localhost"

func main() {}

// new for net
var conn *net.UDPConn
var locker = &sync.Mutex{}

//export IMBeginInput
func IMBeginInput() int {
	locker.Lock()
	defer locker.Unlock()
	if conn == nil {
		raddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", HOST, PORT))
		if err != nil {
			return 1
		}
		laddr, err := net.ResolveUDPAddr("udp", "localhost:0")
		if err != nil {
			return 1
		}
		conn, err = net.DialUDP("udp", laddr, raddr)
		if err != nil {
			return 1
		}
	}
	_, err := conn.Write([]byte("Begin\n"))
	if err != nil {
		return 1
	}
	return 0
}

//export IMEndInput
func IMEndInput() {
	locker.Lock()
	defer locker.Unlock()
	conn.Write([]byte("End\n"))
}

//export IMNetRead
func IMNetRead() *C.char {
	//返回值用完后应该free
	//locker.Lock()
	//defer locker.Unlock()
	if conn == nil {
		return nil
	}
	var buf [128]byte
	conn.SetReadDeadline(time.Now().Add(time.Second * 10))
	n, _, err := conn.ReadFromUDP(buf[:])
	if err != nil {
		return nil
	}
	msg := buf[0:n]
	return C.CString(string(msg))
}

var status = &atomic.Int32{}

//export IMResetStatus
func IMResetStatus() {
	status.Store(0)
}

//export IMGetStatus
func IMGetStatus() int32 {
	return status.Load()
}

//export IMShiftStatus
func IMShiftStatus() {
	status.Store((status.Load() + 1) % 3)
}
